package edu.tjut.tjutcommunity.controller;


import com.aliyun.oss.OSS;
import edu.tjut.tjutcommunity.utils.UploadUtils;
import edu.tjut.tjutcommunity.entity.Message;
import edu.tjut.tjutcommunity.entity.Pair;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

@RestController
public class UpLoad {
    private final OSS ossClient;
    private final UploadUtils uUtils;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public UpLoad(OSS ossClient, UploadUtils uUtils) {
        this.ossClient = ossClient;
        this.uUtils = uUtils;
    }

//    @RequestMapping("/upload")
//    public Message upload(@RequestParam("file") MultipartFile file, @RequestParam("ordinal") Integer ordinal, @RequestParam("type") Integer type) {
//        //获取用户token，根据token获取用户id
//        String stuId = UserUtil.getCurStuId();
//        //如果文件不为空，写入上传路径
//        if (!file.isEmpty()) {
//            String url = uUtils.uploadImage(ossClient, file, "tjutCommunityPost");
//            //将url存入redis中。
//            try {
//                String key = null;
//                if (type == 0)
//                    key = stuId + "_post_pic_" + ordinal;
//                else if (type == 1) key = stuId + "_floor_pic_" + ordinal;
//                else return Message.failed();
//                stringRedisTemplate.opsForValue().set(key, url, 60 * 10, TimeUnit.SECONDS);
//            } catch (Exception e) {
//                return Message.failed();
//            }
//            return Message.ok(new Pair<>("url", url));
//        }
//        return Message.failed("文件为空");
//    }
    @RequestMapping("/upload")
    public Message upload(@RequestParam("file") MultipartFile file) {
        //如果文件不为空，写入上传路径
        if (!file.isEmpty()) {
            String url = uUtils.uploadImage(ossClient, file, "tjutCommunityPost");
            return Message.ok(url);
        }
        return Message.failed("文件为空");
    }


}
